package com.bestcem.xm.component.security.auth;

import com.bestcem.bp.xm.user.grpc.v1.services.CheckAuthRequest;
import com.bestcem.bp.xm.user.grpc.v1.services.CheckAuthResponse;
import com.bestcem.bp.xm.user.grpc.v1.services.Token;
import com.bestcem.bp.xm.user.grpc.v1.services.UserAuthServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.component.security.dto.AuthenticationDTO;
import com.bestcem.xm.component.security.dto.TokenDTO;
import io.grpc.Status;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class XmAuthClient {

    @GrpcClient(GrpcClientNames.DS_USER)
    private UserAuthServiceGrpc.UserAuthServiceBlockingStub stub;

    public ServiceResult<AuthenticationDTO> checkAuthentication(String token, Boolean authentication, String uri,
                                                                String method) {
        CheckAuthResponse response = stub.checkAuth(CheckAuthRequest.newBuilder()
                .setToken(token).setAuthentication(authentication).setUri(uri).setMethod(method).build());
        if (response.getStatus().getCodeValue() != Status.Code.OK.value()) {
            log.error("auth failed, unknown error, token: {}, authentication: {}, uri: {}, method: {}, response: {}",
                    token, authentication, uri, method, response);
            return ServiceResult.fail("鉴权失败");
        }

        AuthenticationDTO dto = new AuthenticationDTO();
        dto.setPermission(response.getPermission());
        dto.setToken(this.toTokenDTO(response.getToken()));
        return ServiceResult.success(dto);

    }

    /**
     * 类型转换
     *
     * @param token
     * @return
     */
    private TokenDTO toTokenDTO(Token token) {
        TokenDTO dto = new TokenDTO();
        dto.setAvatar(token.getAvatar());
        //dto.setExpiredTime(token.getExpiredTime());
        dto.setOmRole(token.getOm() ? 1 : 0);
        dto.setOrgCode(token.getOrgCode());
        dto.setOrgId(token.getOrgId());
        dto.setRealName(token.getName());
        dto.setSuperRole(token.getSuper() ? 1 : 0);
        dto.setUserId(token.getUserId());
        dto.setIsSenior(token.getSenior() ? 1 : 0);
        return dto;
    }
}
